home *** CD-ROM | disk | FTP | other *** search
/ Download Now 8 / Download Now V8.iso / Program / InternetTools / ApacheWebServer1.3.6 / apache_1_3_6_win32.exe / _SETUP.1 / suexec.c < prev    next >
Encoding:
C/C++ Source or Header  |  1999-02-21  |  16.1 KB  |  566 lines

  1. /* ====================================================================
  2.  * Copyright (c) 1995-1999 The Apache Group.  All rights reserved.
  3.  *
  4.  * Redistribution and use in source and binary forms, with or without
  5.  * modification, are permitted provided that the following conditions
  6.  * are met:
  7.  *
  8.  * 1. Redistributions of source code must retain the above copyright
  9.  *    notice, this list of conditions and the following disclaimer. 
  10.  *
  11.  * 2. Redistributions in binary form must reproduce the above copyright
  12.  *    notice, this list of conditions and the following disclaimer in
  13.  *    the documentation and/or other materials provided with the
  14.  *    distribution.
  15.  *
  16.  * 3. All advertising materials mentioning features or use of this
  17.  *    software must display the following acknowledgment:
  18.  *    "This product includes software developed by the Apache Group
  19.  *    for use in the Apache HTTP server project (http://www.apache.org/)."
  20.  *
  21.  * 4. The names "Apache Server" and "Apache Group" must not be used to
  22.  *    endorse or promote products derived from this software without
  23.  *    prior written permission. For written permission, please contact
  24.  *    apache@apache.org.
  25.  *
  26.  * 5. Products derived from this software may not be called "Apache"
  27.  *    nor may "Apache" appear in their names without prior written
  28.  *    permission of the Apache Group.
  29.  *
  30.  * 6. Redistributions of any form whatsoever must retain the following
  31.  *    acknowledgment:
  32.  *    "This product includes software developed by the Apache Group
  33.  *    for use in the Apache HTTP server project (http://www.apache.org/)."
  34.  *
  35.  * THIS SOFTWARE IS PROVIDED BY THE APACHE GROUP ``AS IS'' AND ANY
  36.  * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  37.  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
  38.  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE APACHE GROUP OR
  39.  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  40.  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
  41.  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  42.  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  43.  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
  44.  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  45.  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
  46.  * OF THE POSSIBILITY OF SUCH DAMAGE.
  47.  * ====================================================================
  48.  *
  49.  * This software consists of voluntary contributions made by many
  50.  * individuals on behalf of the Apache Group and was originally based
  51.  * on public domain software written at the National Center for
  52.  * Supercomputing Applications, University of Illinois, Urbana-Champaign.
  53.  * For more information on the Apache Group and the Apache HTTP server
  54.  * project, please see <http://www.apache.org/>.
  55.  *
  56.  */
  57.  
  58. /*
  59.  * suexec.c -- "Wrapper" support program for suEXEC behaviour for Apache
  60.  *
  61.  ***********************************************************************
  62.  *
  63.  * NOTE! : DO NOT edit this code!!!  Unless you know what you are doing,
  64.  *         editing this code might open up your system in unexpected 
  65.  *         ways to would-be crackers.  Every precaution has been taken 
  66.  *         to make this code as safe as possible; alter it at your own
  67.  *         risk.
  68.  *
  69.  ***********************************************************************
  70.  *
  71.  *
  72.  */
  73.  
  74. #include "ap_config.h"
  75. #include <sys/param.h>
  76. #include <sys/stat.h>
  77. #include <sys/types.h>
  78.  
  79. #include <stdarg.h>
  80.  
  81. #include "suexec.h"
  82.  
  83. /*
  84.  ***********************************************************************
  85.  * There is no initgroups() in QNX, so I believe this is safe :-)
  86.  * Use cc -osuexec -3 -O -mf -DQNX suexec.c to compile.
  87.  *
  88.  * May 17, 1997.
  89.  * Igor N. Kovalenko -- infoh@mail.wplus.net
  90.  ***********************************************************************
  91.  */
  92.  
  93. #if defined(NEED_INITGROUPS)
  94. int initgroups(const char *name, gid_t basegid)
  95. {
  96. /* QNX and MPE do not appear to support supplementary groups. */
  97.     return 0;
  98. }
  99. #endif
  100.  
  101. #if defined(PATH_MAX)
  102. #define AP_MAXPATH PATH_MAX
  103. #elif defined(MAXPATHLEN)
  104. #define AP_MAXPATH MAXPATHLEN
  105. #else
  106. #define AP_MAXPATH 8192
  107. #endif
  108.  
  109. #define AP_ENVBUF 256
  110.  
  111. extern char **environ;
  112. static FILE *log = NULL;
  113.  
  114. char *safe_env_lst[] =
  115. {
  116.     "AUTH_TYPE",
  117.     "CONTENT_LENGTH",
  118.     "CONTENT_TYPE",
  119.     "DATE_GMT",
  120.     "DATE_LOCAL",
  121.     "DOCUMENT_NAME",
  122.     "DOCUMENT_PATH_INFO",
  123.     "DOCUMENT_ROOT",
  124.     "DOCUMENT_URI",
  125.     "FILEPATH_INFO",
  126.     "GATEWAY_INTERFACE",
  127.     "LAST_MODIFIED",
  128.     "PATH_INFO",
  129.     "PATH_TRANSLATED",
  130.     "QUERY_STRING",
  131.     "QUERY_STRING_UNESCAPED",
  132.     "REMOTE_ADDR",
  133.     "REMOTE_HOST",
  134.     "REMOTE_IDENT",
  135.     "REMOTE_PORT",
  136.     "REMOTE_USER",
  137.     "REDIRECT_QUERY_STRING",
  138.     "REDIRECT_STATUS",
  139.     "REDIRECT_URL",
  140.     "REQUEST_METHOD",
  141.     "REQUEST_URI",
  142.     "SCRIPT_FILENAME",
  143.     "SCRIPT_NAME",
  144.     "SCRIPT_URI",
  145.     "SCRIPT_URL",
  146.     "SERVER_ADMIN",
  147.     "SERVER_NAME",
  148.     "SERVER_PORT",
  149.     "SERVER_PROTOCOL",
  150.     "SERVER_SOFTWARE",
  151.     "UNIQUE_ID",
  152.     "USER_NAME",
  153.     "TZ",
  154.     NULL
  155. };
  156.  
  157.  
  158. static void err_output(const char *fmt, va_list ap)
  159. {
  160. #ifdef LOG_EXEC
  161.     time_t timevar;
  162.     struct tm *lt;
  163.  
  164.     if (!log) {
  165.     if ((log = fopen(LOG_EXEC, "a")) == NULL) {
  166.         fprintf(stderr, "failed to open log file\n");
  167.         perror("fopen");
  168.         exit(1);
  169.     }
  170.     }
  171.  
  172.     time(&timevar);
  173.     lt = localtime(&timevar);
  174.  
  175.     fprintf(log, "[%d-%.2d-%.2d %.2d:%.2d:%.2d]: ",
  176.         lt->tm_year + 1900, lt->tm_mon + 1, lt->tm_mday,
  177.         lt->tm_hour, lt->tm_min, lt->tm_sec);
  178.  
  179.     vfprintf(log, fmt, ap);
  180.  
  181.     fflush(log);
  182. #endif /* LOG_EXEC */
  183.     return;
  184. }
  185.  
  186. static void log_err(const char *fmt,...)
  187. {
  188. #ifdef LOG_EXEC
  189.     va_list ap;
  190.  
  191.     va_start(ap, fmt);
  192.     err_output(fmt, ap);
  193.     va_end(ap);
  194. #endif /* LOG_EXEC */
  195.     return;
  196. }
  197.  
  198. static void clean_env(void)
  199. {
  200.     char pathbuf[512];
  201.     char **cleanenv;
  202.     char **ep;
  203.     int cidx = 0;
  204.     int idx;
  205.  
  206.  
  207.     if ((cleanenv = (char **) calloc(AP_ENVBUF, sizeof(char *))) == NULL) {
  208.         log_err("failed to malloc memory for environment\n");
  209.     exit(120);
  210.     }
  211.  
  212.     sprintf(pathbuf, "PATH=%s", SAFE_PATH);
  213.     cleanenv[cidx] = strdup(pathbuf);
  214.     cidx++;
  215.  
  216.     for (ep = environ; *ep && cidx < AP_ENVBUF-1; ep++) {
  217.     if (!strncmp(*ep, "HTTP_", 5)) {
  218.         cleanenv[cidx] = *ep;
  219.         cidx++;
  220.     }
  221.     else {
  222.         for (idx = 0; safe_env_lst[idx]; idx++) {
  223.         if (!strncmp(*ep, safe_env_lst[idx],
  224.                  strlen(safe_env_lst[idx]))) {
  225.             cleanenv[cidx] = *ep;
  226.             cidx++;
  227.             break;
  228.         }
  229.         }
  230.     }
  231.     }
  232.  
  233.     cleanenv[cidx] = NULL;
  234.  
  235.     environ = cleanenv;
  236. }
  237.  
  238. int main(int argc, char *argv[])
  239. {
  240.     int userdir = 0;        /* ~userdir flag             */
  241.     uid_t uid;            /* user information          */
  242.     gid_t gid;            /* target group placeholder  */
  243.     char *target_uname;        /* target user name          */
  244.     char *target_gname;        /* target group name         */
  245.     char *target_homedir;    /* target home directory     */
  246.     char *actual_uname;        /* actual user name          */
  247.     char *actual_gname;        /* actual group name         */
  248.     char *prog;            /* name of this program      */
  249.     char *cmd;            /* command to be executed    */
  250.     char cwd[AP_MAXPATH];    /* current working directory */
  251.     char dwd[AP_MAXPATH];    /* docroot working directory */
  252.     struct passwd *pw;        /* password entry holder     */
  253.     struct group *gr;        /* group entry holder        */
  254.     struct stat dir_info;    /* directory info holder     */
  255.     struct stat prg_info;    /* program info holder       */
  256.  
  257.     /*
  258.      * If there are a proper number of arguments, set
  259.      * all of them to variables.  Otherwise, error out.
  260.      */
  261.     prog = argv[0];
  262.     if (argc < 4) {
  263.     log_err("too few arguments\n");
  264.     exit(101);
  265.     }
  266.     target_uname = argv[1];
  267.     target_gname = argv[2];
  268.     cmd = argv[3];
  269.  
  270.     /*
  271.      * Check existence/validity of the UID of the user
  272.      * running this program.  Error out if invalid.
  273.      */
  274.     uid = getuid();
  275.     if ((pw = getpwuid(uid)) == NULL) {
  276.     log_err("invalid uid: (%ld)\n", uid);
  277.     exit(102);
  278.     }
  279.  
  280.     /*
  281.      * Check to see if the user running this program
  282.      * is the user allowed to do so as defined in
  283.      * suexec.h.  If not the allowed user, error out.
  284.      */
  285. #ifdef _OSD_POSIX
  286.     /* User name comparisons are case insensitive on BS2000/OSD */
  287.     if (strcasecmp(HTTPD_USER, pw->pw_name)) {
  288.         log_err("user mismatch (%s instead of %s)\n", pw->pw_name, HTTPD_USER);
  289.     exit(103);
  290.     }
  291. #else  /*_OSD_POSIX*/
  292.     if (strcmp(HTTPD_USER, pw->pw_name)) {
  293.         log_err("user mismatch (%s instead of %s)\n", pw->pw_name, HTTPD_USER);
  294.     exit(103);
  295.     }
  296. #endif /*_OSD_POSIX*/
  297.  
  298.     /*
  299.      * Check for a leading '/' (absolute path) in the command to be executed,
  300.      * or attempts to back up out of the current directory,
  301.      * to protect against attacks.  If any are
  302.      * found, error out.  Naughty naughty crackers.
  303.      */
  304.     if ((cmd[0] == '/') || (!strncmp(cmd, "../", 3))
  305.     || (strstr(cmd, "/../") != NULL)) {
  306.         log_err("invalid command (%s)\n", cmd);
  307.     exit(104);
  308.     }
  309.  
  310.     /*
  311.      * Check to see if this is a ~userdir request.  If
  312.      * so, set the flag, and remove the '~' from the
  313.      * target username.
  314.      */
  315.     if (!strncmp("~", target_uname, 1)) {
  316.     target_uname++;
  317.     userdir = 1;
  318.     }
  319.  
  320.     /*
  321.      * Error out if the target username is invalid.
  322.      */
  323.     if ((pw = getpwnam(target_uname)) == NULL) {
  324.     log_err("invalid target user name: (%s)\n", target_uname);
  325.     exit(105);
  326.     }
  327.  
  328.     /*
  329.      * Error out if the target group name is invalid.
  330.      */
  331.     if (strspn(target_gname, "1234567890") != strlen(target_gname)) {
  332.     if ((gr = getgrnam(target_gname)) == NULL) {
  333.         log_err("invalid target group name: (%s)\n", target_gname);
  334.         exit(106);
  335.     }
  336.     gid = gr->gr_gid;
  337.     actual_gname = strdup(gr->gr_name);
  338.     }
  339.     else {
  340.     gid = atoi(target_gname);
  341.     actual_gname = strdup(target_gname);
  342.     }
  343.  
  344. #ifdef _OSD_POSIX
  345.     /*
  346.      * Initialize BS2000 user environment
  347.      */
  348.     {
  349.     pid_t pid;
  350.     int status;
  351.  
  352.     switch (pid = ufork(target_uname))
  353.     {
  354.     case -1:    /* Error */
  355.         log_err("failed to setup bs2000 environment for user %s: %s\n",
  356.             target_uname, strerror(errno));
  357.         exit(150);
  358.     case 0:    /* Child */
  359.         break;
  360.     default:    /* Father */
  361.         while (pid != waitpid(pid, &status, 0))
  362.         ;
  363.         /* @@@ FIXME: should we deal with STOP signals as well? */
  364.         if (WIFSIGNALED(status))
  365.         kill (getpid(), WTERMSIG(status));
  366.         exit(WEXITSTATUS(status));
  367.     }
  368.     }
  369. #endif /*_OSD_POSIX*/
  370.  
  371.     /*
  372.      * Save these for later since initgroups will hose the struct
  373.      */
  374.     uid = pw->pw_uid;
  375.     actual_uname = strdup(pw->pw_name);
  376.     target_homedir = strdup(pw->pw_dir);
  377.  
  378.     /*
  379.      * Log the transaction here to be sure we have an open log 
  380.      * before we setuid().
  381.      */
  382.     log_err("uid: (%s/%s) gid: (%s/%s) cmd: %s\n",
  383.         target_uname, actual_uname,
  384.         target_gname, actual_gname,
  385.         cmd);
  386.  
  387.     /*
  388.      * Error out if attempt is made to execute as root or as
  389.      * a UID less than UID_MIN.  Tsk tsk.
  390.      */
  391.     if ((uid == 0) || (uid < UID_MIN)) {
  392.     log_err("cannot run as forbidden uid (%d/%s)\n", uid, cmd);
  393.     exit(107);
  394.     }
  395.  
  396.     /*
  397.      * Error out if attempt is made to execute as root group
  398.      * or as a GID less than GID_MIN.  Tsk tsk.
  399.      */
  400.     if ((gid == 0) || (gid < GID_MIN)) {
  401.     log_err("cannot run as forbidden gid (%d/%s)\n", gid, cmd);
  402.     exit(108);
  403.     }
  404.  
  405.     /*
  406.      * Change UID/GID here so that the following tests work over NFS.
  407.      *
  408.      * Initialize the group access list for the target user,
  409.      * and setgid() to the target group. If unsuccessful, error out.
  410.      */
  411.     if (((setgid(gid)) != 0) || (initgroups(actual_uname, gid) != 0)) {
  412.     log_err("failed to setgid (%ld: %s)\n", gid, cmd);
  413.     exit(109);
  414.     }
  415.  
  416.     /*
  417.      * setuid() to the target user.  Error out on fail.
  418.      */
  419.     if ((setuid(uid)) != 0) {
  420.     log_err("failed to setuid (%ld: %s)\n", uid, cmd);
  421.     exit(110);
  422.     }
  423.  
  424.     /*
  425.      * Get the current working directory, as well as the proper
  426.      * document root (dependant upon whether or not it is a
  427.      * ~userdir request).  Error out if we cannot get either one,
  428.      * or if the current working directory is not in the docroot.
  429.      * Use chdir()s and getcwd()s to avoid problems with symlinked
  430.      * directories.  Yuck.
  431.      */
  432.     if (getcwd(cwd, AP_MAXPATH) == NULL) {
  433.     log_err("cannot get current working directory\n");
  434.     exit(111);
  435.     }
  436.  
  437.     if (userdir) {
  438.     if (((chdir(target_homedir)) != 0) ||
  439.         ((chdir(USERDIR_SUFFIX)) != 0) ||
  440.         ((getcwd(dwd, AP_MAXPATH)) == NULL) ||
  441.         ((chdir(cwd)) != 0)) {
  442.         log_err("cannot get docroot information (%s)\n", target_homedir);
  443.         exit(112);
  444.     }
  445.     }
  446.     else {
  447.     if (((chdir(DOC_ROOT)) != 0) ||
  448.         ((getcwd(dwd, AP_MAXPATH)) == NULL) ||
  449.         ((chdir(cwd)) != 0)) {
  450.         log_err("cannot get docroot information (%s)\n", DOC_ROOT);
  451.         exit(113);
  452.     }
  453.     }
  454.  
  455.     if ((strncmp(cwd, dwd, strlen(dwd))) != 0) {
  456.     log_err("command not in docroot (%s/%s)\n", cwd, cmd);
  457.     exit(114);
  458.     }
  459.  
  460.     /*
  461.      * Stat the cwd and verify it is a directory, or error out.
  462.      */
  463.     if (((lstat(cwd, &dir_info)) != 0) || !(S_ISDIR(dir_info.st_mode))) {
  464.     log_err("cannot stat directory: (%s)\n", cwd);
  465.     exit(115);
  466.     }
  467.  
  468.     /*
  469.      * Error out if cwd is writable by others.
  470.      */
  471.     if ((dir_info.st_mode & S_IWOTH) || (dir_info.st_mode & S_IWGRP)) {
  472.     log_err("directory is writable by others: (%s)\n", cwd);
  473.     exit(116);
  474.     }
  475.  
  476.     /*
  477.      * Error out if we cannot stat the program.
  478.      */
  479.     if (((lstat(cmd, &prg_info)) != 0) || (S_ISLNK(prg_info.st_mode))) {
  480.     log_err("cannot stat program: (%s)\n", cmd);
  481.     exit(117);
  482.     }
  483.  
  484.     /*
  485.      * Error out if the program is writable by others.
  486.      */
  487.     if ((prg_info.st_mode & S_IWOTH) || (prg_info.st_mode & S_IWGRP)) {
  488.     log_err("file is writable by others: (%s/%s)\n", cwd, cmd);
  489.     exit(118);
  490.     }
  491.  
  492.     /*
  493.      * Error out if the file is setuid or setgid.
  494.      */
  495.     if ((prg_info.st_mode & S_ISUID) || (prg_info.st_mode & S_ISGID)) {
  496.     log_err("file is either setuid or setgid: (%s/%s)\n", cwd, cmd);
  497.     exit(119);
  498.     }
  499.  
  500.     /*
  501.      * Error out if the target name/group is different from
  502.      * the name/group of the cwd or the program.
  503.      */
  504.     if ((uid != dir_info.st_uid) ||
  505.     (gid != dir_info.st_gid) ||
  506.     (uid != prg_info.st_uid) ||
  507.     (gid != prg_info.st_gid)) {
  508.     log_err("target uid/gid (%ld/%ld) mismatch "
  509.         "with directory (%ld/%ld) or program (%ld/%ld)\n",
  510.         uid, gid,
  511.         dir_info.st_uid, dir_info.st_gid,
  512.         prg_info.st_uid, prg_info.st_gid);
  513.     exit(120);
  514.     }
  515.     /*
  516.      * Error out if the program is not executable for the user.
  517.      * Otherwise, she won't find any error in the logs except for
  518.      * "[error] Premature end of script headers: ..."
  519.      */
  520.     if (!(prg_info.st_mode & S_IXUSR)) {
  521.     log_err("file has no execute permission: (%s/%s)\n", cwd, cmd);
  522.     exit(121);
  523.     }
  524.  
  525.     clean_env();
  526.  
  527.     /* 
  528.      * Be sure to close the log file so the CGI can't
  529.      * mess with it.  If the exec fails, it will be reopened 
  530.      * automatically when log_err is called.  Note that the log
  531.      * might not actually be open if LOG_EXEC isn't defined.
  532.      * However, the "log" cell isn't ifdef'd so let's be defensive
  533.      * and assume someone might have done something with it
  534.      * outside an ifdef'd LOG_EXEC block.
  535.      */
  536.     if (log != NULL) {
  537.     fclose(log);
  538.     log = NULL;
  539.     }
  540.  
  541.     /*
  542.      * Execute the command, replacing our image with its own.
  543.      */
  544. #ifdef NEED_HASHBANG_EMUL
  545.     /* We need the #! emulation when we want to execute scripts */
  546.     {
  547.     extern char **environ;
  548.  
  549.     ap_execve(cmd, &argv[3], environ);
  550.     }
  551. #else /*NEED_HASHBANG_EMUL*/
  552.     execv(cmd, &argv[3]);
  553. #endif /*NEED_HASHBANG_EMUL*/
  554.  
  555.     /*
  556.      * (I can't help myself...sorry.)
  557.      *
  558.      * Uh oh.  Still here.  Where's the kaboom?  There was supposed to be an
  559.      * EARTH-shattering kaboom!
  560.      *
  561.      * Oh well, log the failure and error out.
  562.      */
  563.     log_err("(%d)%s: exec failed (%s)\n", errno, strerror(errno), cmd);
  564.     exit(255);
  565. }
  566.